package com.nny.alarm.edit;

import android.os.Handler;
import android.os.Message;

import com.nny.alarm.audio.RingPlayer;
import com.nny.alarm.edit.adapter.RingAdapter;
import com.nny.alarm.widget.DialView;
import com.uxwine.alarm.alert.RingManager;
import com.uxwine.widget.ActionDialog;
import com.uxwine.widget.ActionDialog.OnActionListener;

public class RingEditor implements IAlarmEditor, OnActionListener
{
	AlarmEditor mEditor;
	DialAdapter mAdapter;
	RingPlayer mRing;
	MHandler mHandler;
	
	private static final int MSG_PLAYRING = 1;
	
	public RingEditor(AlarmEditor a)
	{
		mEditor = a;
		mRing = new RingPlayer(a.mCtx);
		mHandler = new MHandler();
	}

	@Override
	public void edit()
	{
		final DialView dtv = mEditor.mDial;
		final int type = RingManager.getRingType(mEditor.mAlarm.alert);
		int id = 7;
		if(type == RingManager.TYPE_SYSTEM)
			id = RingManager.getRingId(mEditor.mAlarm.alert);
		
		showDial(id);
	}

	@Override
	public boolean next()
	{
		stop();
		mEditor.step(AlarmEditor.STEP_CYCLE);
		return true;
	}

	@Override
	public void onMarked(int index)
	{
		stop();
		if(index == 7)
		{
			selectLocal();
		}
		else
		{			
			mEditor.mAlarm.alert = RingManager.getRingUri(index);
			mHandler.sendEmptyMessageDelayed(MSG_PLAYRING, 1000);
		}
	}
	
	private void showDial(int id)
	{
		final DialView dtv = mEditor.mDial;
		mAdapter = new RingAdapter(mEditor.mCtx, id);
		dtv.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
	}
	
	public void selectLocal()
	{
		RingtoneDialog dlg = new RingtoneDialog(mEditor, this);
		dlg.setOnActionListener(this);
		dlg.show();
	}

	@Override
	public void onMarkChange(int index)
	{
		
	}
	
	public void stop()
	{
		mHandler.removeMessages(MSG_PLAYRING);
		mRing.stop();
	}

	private class MHandler extends Handler
	{

		@Override
		public void handleMessage(Message msg) {
			if(msg.what == MSG_PLAYRING)
			{
				mRing.play((int)mAdapter.getValue(mAdapter.getPosition()));
			}
		}
	}

	@Override
	public void over()
	{
		stop();
	}

	@Override
	public void reset()
	{
		
	}

	@Override
	public void onExit(int code)
	{
		if(code == ActionDialog.ACTION_CANCEL)
		{
			int type = RingManager.getRingType(mEditor.mAlarm.alert);
			if(type == RingManager.TYPE_SYSTEM)
			{
				int id = RingManager.getRingId(mEditor.mAlarm.alert);
				showDial(id);
			}
		}
	}
	
	
}
